package cn.schoolwow.quickdao.module.database.dml.instance.flow.update.flow;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.instance.QueryInstance;

import java.util.ArrayList;
import java.util.List;

public class SetUpdateInstanceParameterFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        Object instance = flowContext.checkData("instance");
        List<Property> setPropertyList = flowContext.checkData("setPropertyList", List.class);
        List<Property> wherePropertyList = flowContext.checkData("wherePropertyList", List.class);

        List<Object> parameters = new ArrayList();
        for(Property property:setPropertyList){
            Object value = null;
            if (null != quickDAOConfig.databaseOption.updateColumnValueFunction) {
                value = quickDAOConfig.databaseOption.updateColumnValueFunction.apply(property);
            }
            if (null == value) {
                value = QueryInstance.newQuery(instance)
                        .execute()
                        .getSingleFieldValue(property.name);
            }
            parameters.add(value);
        }
        for(Property property:wherePropertyList){
            Object value = QueryInstance.newQuery(instance)
                    .execute()
                    .getSingleFieldValue(property.name);
            if(null==value){
                throw new IllegalArgumentException("唯一字段不能为空!实例类名:"+instance.getClass().getName()+",字段名:"+property.name);
            }
            parameters.add(value);
        }
        flowContext.putTemporaryData("parameters", parameters);
    }

    @Override
    public String name() {
        return "更新实例-设置SQL语句参数列表";
    }

}
